package com.hanoi.wiki.manager.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.hanoi.wiki.dao.BlocksDAO;
import com.hanoi.wiki.dao.CoordinatesDAO;
import com.hanoi.wiki.exception.DataAccessException;
import com.hanoi.wiki.manager.BlocksManager;
import com.hanoi.wiki.model.Blocks;
import com.hanoi.wiki.model.Coordinates;
import com.hanoi.wiki.model.json.BlocksJson;

@Component
@Transactional
public class BlocksManagerImpl extends BaseManagerImpl implements BlocksManager{

	@Autowired
	private BlocksDAO blocksDao;
	
	@Autowired
	private CoordinatesDAO coordinatesDAO;
	
	public int save(BlocksJson json) {
		try {
			Blocks blocks = new Blocks(json);
			
			List<Coordinates> list = new ArrayList<Coordinates>();
			Coordinates coordinates;
			for(int i : json.getCoordinates()) {
				coordinates = coordinatesDAO.get(i);
				if (coordinates != null) {
					list.add(coordinates);
				}
			}
			
			blocks.setCoordinates(list);
			return blocksDao.saveBlocks(blocks);
		} catch (DataAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		return 0;
	}

	
	public void update(BlocksJson json) {
		try {
			Blocks blocks = new Blocks(json);
			
			List<Coordinates> list = new ArrayList<Coordinates>();
			Coordinates coordinates;
			for(int i : json.getCoordinates()) {
				coordinates = coordinatesDAO.get(i);
				if (coordinates != null) {
					list.add(coordinates);
				}
			}
			
			blocks.setCoordinates(list);
			blocks.setId(json.getId());
			
			blocksDao.update(blocks);
		} catch (DataAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
	public BlocksJson get(Integer id) {
		try {
			return new BlocksJson(blocksDao.get(id));
		} catch (DataAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	
	public List<BlocksJson> getList() {
		List<BlocksJson> blockJsonList = new ArrayList<BlocksJson>();
		List<Blocks> blockList = blocksDao.getList();
		try {
			for (Blocks blocks : blockList) {
				blockJsonList.add(new BlocksJson(blocks));
			}
		} catch (DataAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return blockJsonList;
	}

	
	public void remove(Integer id) {
		try {
			if(blocksDao.get(id) != null) {
				blocksDao.remove(id);
			}
		} catch (DataAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
